<template>
  <div class="app-container">
    <avue-crud
      ref="crud"
      v-model="book"
      :page="page"
      :data="tableData"
      :table-loading="tableLoading"
      :option="tableOption"
      :permission="permissionList"
      :before-open="beforeUpdate"
      @on-load="getPage"
      @refresh-change="refreshChange"
      @row-save="handleSave"
      @row-update="handleUpdate"
      @sort-change="sortChange"
      @search-change="searchChange"
      @selection-change="selectionChange"
    >
      <template slot="areaList" slot-scope="scope">
        {{ scope.row.fullAreaText }}
      </template>
      <template slot="serviceOrganization" slot-scope="scope">
        {{ scope.row.serviceOrganizationName }}
      </template>
      <template slot="lonlat" slot-scope="scope">
        {{ scope.row.lon + "," + scope.row.lat }}
      </template>
      <template slot="contractValidity" slot-scope="scope">
        {{
          scope.row.startContractValidity +
          " 至 " +
          scope.row.endContractValidity
        }}
      </template>
      <template slot="state" slot-scope="scope">
        <el-tag
          size="mini"
          effect="dark"
          :type="
            scope.row.state == 0
              ? 'success'
              : scope.row.state == 1
              ? 'danger'
              : 'warning'
          "
        >
          {{ scope.row.$state }}
        </el-tag>
      </template>
      <template slot="stateForm" slot-scope="scope">
        <el-tag
          size="mini"
          effect="dark"
          :type="
            scope.row.state == 0
              ? 'success'
              : scope.row.state == 1
              ? 'danger'
              : 'warning'
          "
        >
          {{ scope.row.$state }}
        </el-tag>
      </template>
      <template slot="homePicture" slot-scope="scope">
        <img-info v-model="scope.row.homePicture" />
      </template>
      <template slot="detailPicture" slot-scope="scope">
        <img-info v-model="scope.row.detailPicture" />
      </template>
      <template slot="areaListForm" slot-scope="scope">
        <el-cascader
          ref="areaTree"
          v-model="scope.row.areaList"
          :props="areaProps"
          @change="changeArea"
        />
      </template>
      <template slot="serviceOrganizationForm" slot-scope="scope">
        <el-select v-model="scope.row.serviceOrganization" placeholder="请选择">
          <el-option
            v-for="item in organizationList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </template>
      <template slot="contractValidityForm" slot-scope="scope">
        <el-date-picker
          v-model="scope.row.contractValidity"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          @change="changeDate"
        />
      </template>
      <template slot="homePictureForm" slot-scope="scope">
        <upload-img
          v-model="scope.row.homePicture"
          :operate="operate"
          :limit="1"
        />
      </template>
      <template slot="detailPictureForm" slot-scope="scope">
        <upload-img v-model="scope.row.detailPicture" :operate="operate" />
      </template>
      <template slot="lonlatForm" slot-scope="scope">
        <el-input v-model="scope.row.lonlat" readonly>
          <el-button slot="append" @click="showMap = true">选择</el-button>
        </el-input>
      </template>
    </avue-crud>
  </div>
</template>

<script>
import { checkPermi, checkRole } from "@/utils/permission";
import {
  getPage,
  getObj,
  addObj,
  putObj,
  delObj,
  updateStatus,
} from "@/api/book/manage";
import { getAll } from "@/api/book/organization";
import { tableOption } from "@/const/crud/book/manage";
import axios from "axios";
export default {
  name: "BookManage",
  data() {
    const id = 0;
    return {
      book: {},
      // book: {
      //   name: "张三书院",
      //   briefIntroduction: "13333",
      //   type: 4,
      //   typeOther: "other",
      //   detailedAddress: "五道口",
      //   contacts: "张三",
      //   contactPhone: "15157751351",
      //   completedTime: "1993-09-09",
      //   company: "国家队",
      //   area: "123.12",

      //   areaList: [],
      // },
      tableData: [],
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20, // 每页显示多少条
        ascs: [],
        descs: "subscribe_time",
      },
      paramsSearch: {},
      tableLoading: false,
      tableOption: tableOption,
      selectionData: [],
      areaOptions: [],
      areaProps: {
        value: "areaCode",
        label: "areaName",
        lazy: true,
        lazyLoad(node, resolve) {
          const { level } = node;
          let parentArea = "100000";

          if (level !== 0) {
            parentArea = node.value;
          }
          axios
            .get("/v3/config/district", {
              params: {
                keywords: parentArea,
                subdistrict: 1,
                key: "5c5474605da0c21199de170e5f48c679",
              },
            })
            .then((res) => {
              const data = res.data.districts[0].districts.map((item) => {
                return {
                  areaCode: item.level === "street" ? item.name : item.adcode,
                  areaName: item.name,
                  leaf: level === 3,
                };
              });
              resolve(data);
            });
        },
      },
      organizationList: [],
      showMap: false,
      operate: "",
    };
  },
  computed: {
    permissionList() {
      return {
        addBtn: checkPermi(["book:manage:add"]),
        editBtn: checkPermi(["book:manage:edit"]),
        viewBtn: checkPermi(["book:manage:get"]),
      };
    },
  },
  watch: {
    "book.type"(val) {
      const column = this.tableOption.column[4];
      if (val === 4) {
        column.addDisplay = true;
        column.editDisplay = true;
      } else {
        column.addDisplay = false;
        column.editDisplay = false;
        this.book.typeOther = undefined;
      }
    },
  },
  created() {
    getAll().then((res) => {
      this.organizationList = res.data;
    });
  },
  methods: {
    beforeUpdate(done, type) {
      this.operate = type;
      if (type !== "add") {
        const row = this.book;
        row.areaList = [
          row.provinceCode,
          row.cityCode,
          row.areaCode,
          row.streetCode,
        ];
        row.contractValidity = [
          row.startContractValidity,
          row.endContractValidity,
        ];
        row.lonlat = row.lon + "," + row.lat;
      }
      done();
    },
    changeArea(val) {
      console.log(val);
      if (val.length) {
        const [provinceCode, cityCode, areaCode, streetCode] = val;
        this.book.provinceCode = provinceCode;
        this.book.cityCode = cityCode;
        this.book.areaCode = areaCode;
        this.book.streetCode = streetCode;
        this.$nextTick(() => {
          this.book.fullAreaText = this.$refs.areaTree.presentText.replaceAll(
            " / ",
            ""
          );
        });
      }
    },
    changeDate(val) {
      this.book.startContractValidity = val[0];
      this.book.endContractValidity = val[1];
    },
    callback(data) {
      console.log(data);
      this.book.lon = data.lng;
      this.book.lat = data.lat;
      this.book.lonlat = data.lng + "," + data.lat;
    },
    selectionChange(list) {
      this.selectionData = list;
    },
    searchChange(params, done) {
      params = this.filterForm(params);
      //console.log(params, this.filterForm, "filterForm");
      this.paramsSearch = params;
      this.page.currentPage = 1;
      this.getPage(this.page, params);
      done();
    },
    sortChange(val) {
      const prop = val.prop
        ? val.prop.replace(/([A-Z])/g, "_$1").toLowerCase()
        : "";
      if (val.order == "ascending") {
        this.page.descs = [];
        this.page.ascs = prop;
      } else if (val.order == "descending") {
        this.page.ascs = [];
        this.page.descs = prop;
      } else {
        this.page.ascs = [];
        this.page.descs = [];
      }
      this.getPage(this.page);
    },
    getPage(page, params) {
      this.tableLoading = true;
      getPage(
        Object.assign(
          {
            pageNum: page.currentPage,
            pageSize: page.pageSize,
            descs: this.page.descs,
            ascs: this.page.ascs,
            appType: "2",
          },
          params,
          this.paramsSearch
        )
      )
        .then((response) => {
          this.tableData = response.rows;
          this.page.total = response.total;
          this.page.currentPage = page.currentPage;
          this.page.pageSize = page.pageSize;
          this.tableLoading = false;
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },
    handleRefuse(row, type) {
      this.$prompt("请输入拒绝原因", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern: /\S/,
        inputErrorMessage: "输入不能为空",
      }).then(({ value }) => {
        // this.tableLoading = true;
        // row.remark = value;
        // updateRemark(row)
        //   .then((response) => {
        //     this.tableLoading = false;
        //     if (response.code == 200) {
        //       this.tableData.splice(index, 1, Object.assign({}, row));
        //       this.$message({
        //         showClose: true,
        //         message: "修改成功",
        //         type: "success",
        //       });
        //       this.getPage(this.page);
        //     } else {
        //       this.$message.error(response.msg);
        //     }
        //   })
        //   .catch(() => {
        //     this.tableLoading = false;
        //   });
      });
    },
    handlePass: function (row, index) {
      var _this = this;
      this.$confirm("是否确认通过", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "success",
      })
        .then(function () {
          // return delObj(row.id);
        })
        .then((data) => {
          _this.$message({
            showClose: true,
            message: "通过成功",
            type: "success",
          });
          this.getPage(this.page);
        })
        .catch(function (err) {});
    },
    /**
     * @title 数据添加
     * @param row 为当前的数据
     * @param done 为表单关闭函数
     *
     **/
    handleSave: function (row, done, loading) {
      addObj(row)
        .then((data) => {
          this.$message({
            showClose: true,
            message: "添加成功",
            type: "success",
          });
          done();
          this.getPage(this.page);
        })
        .catch(() => {
          loading();
        });
    },
    /**
     * @title 数据更新
     * @param row 为当前的数据
     * @param index 为当前更新数据的行数
     * @param done 为表单关闭函数
     *
     **/
    handleUpdate: function (row, index, done, loading) {
      putObj(row)
        .then((data) => {
          this.$message({
            showClose: true,
            message: "修改成功",
            type: "success",
          });
          done();
          this.getPage(this.page);
        })
        .catch(() => {
          loading();
        });
    },
    /**
     * 刷新回调
     */
    refreshChange(page) {
      this.getPage(this.page);
    },
  },
};
</script>
